/*
 * @Author: g05047
 * @Date: 2020-10-28 16:20:49
 * @LastEditors: g05047
 * @LastEditTime: 2021-07-29 15:14:22
 * @Description: file content
 */
import Vue from 'vue';
/***
 * 防抖 单位时间只触发最后一次
 *  @param {?Number|300} time - 间隔时间
 *  @param {Function} fn - 执行事件
 *  @param {?String|"click"} event - 事件类型 例："click"
 *  @param {Array} binding.value - [fn,event,time]
 *  例：<el-button v-debounce="[reset,`click`,300]">刷新</el-button>
 *  也可简写成：<el-button v-debounce="[reset]">刷新</el-button>
 */
Vue.directive('noClick', {
  inserted(el, binding) {
    el.addEventListener('click', e => {
      el.classList.add('is-disabled');
      el.disabled = true;
      setTimeout(() => {
        el.disabled = false;
        el.classList.remove('is-disabled');
      }, binding.value || 1000);
    });
  },
});

/***
 *  节流 每单位时间可触发一次
 *  第一次瞬间触发，最后一次不管是否达到间隔时间依然触发
 * 【考虑到input的change事件】
 *  @param {?Number|300} time - 间隔时间
 *  @param {Function} fn - 执行事件
 *  @param {?String|"click"} event - 事件类型 例："click"
 *  @param {Array} binding.value - [fn,event,time]
 *  例：<el-button v-throttle="[reset,`click`,300]">刷新</el-button>
 *  传递参数则：<el-button v-throttle="[()=>reset(param),`click`,300]">刷新</el-button>
 */
Vue.directive('throttle', {
  inserted: function(el, binding) {
    let [fn, event = 'click', time = 300] = binding.value;
    let timer, timer_end;
    el.addEventListener(event, () => {
      if (timer) {
        clearTimeout(timer_end);
        return (timer_end = setTimeout(() => fn(), time));
      }
      fn();
      timer = setTimeout(() => (timer = null), time);
    });
  },
});
Vue.directive('title', {
  inserted: function(el, binding) {
    document.title = el.dataset.title;
  },
});
//限制只能输入数字 edit by zh
Vue.directive('enterNumber', {
  inserted: function(el) {
    el.addEventListener('keypress', function(e) {
      e = e || window.event;
      let charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
      let re = /\d/;
      if (
        !re.test(String.fromCharCode(charcode)) &&
        charcode > 9 &&
        !e.ctrlKey
      ) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
    });
  },
});
Vue.directive('enterNumber2', {
  inserted: function(el) {
    el.addEventListener('keypress', function(e) {
      e = e || window.event;
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      let re = /\d/;
      if (charcode == 46) {
        if (el.value.includes('.')) {
          e.preventDefault();
        }
        return;
      } else if (
        !re.test(String.fromCharCode(charcode)) &&
        charcode > 9 &&
        !e.ctrlKey
      ) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
    });
  },
});
Vue.filter('money', function(val) {
  val = val.toString().replace(/\$|\,/g, '');
  if (isNaN(val)) {
    val = '0';
  }
  let sign = val == (val = Math.abs(val));
  val = Math.floor(val * 100 + 0.50000000001);
  let cents = val % 100;
  val = Math.floor(val / 100).toString();
  if (cents < 10) {
    cents = '0' + cents;
  }
  for (var i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
    val =
      val.substring(0, val.length - (4 * i + 3)) +
      ',' +
      val.substring(val.length - (4 * i + 3));
  }
  return (sign ? '' : '-') + val + '.' + cents;
});

// 只允许输入正整数
Vue.directive('number', {
  bind(el, binding, vnode) {
    let input = vnode.elm.children[0];
    input.addEventListener('compositionstart', () => {
      vnode.inputLocking = true;
    });
    input.addEventListener('compositionend', () => {
      vnode.inputLocking = false;
      input.dispatchEvent(new Event('input'));
    });
    input.addEventListener('input', () => {
      if (vnode.inputLocking) {
        return;
      }
      let oldValue = input.value;
      let newValue = input.value.replace(/[^\d]/g, '');
      if (newValue) {
        switch (binding.value) {
          case 'zeroBefore':
            break; // 数字随意输，不做处理，如 000013
          case 'zeroCan':
            newValue = Number(newValue).toString(); // 去掉开头0 正整数 + 0
            break;
          default:
            newValue = newValue.replace(/^\b(0+)/gi, ''); // （默认）去掉开头0 正整数
        }
      }
      // 判断是否需要更新，避免进入死循环
      if (newValue !== oldValue) {
        input.value = newValue;
        // 通知v-model更新 vue底层双向绑定实现的原理是基于监听input事件
        input.dispatchEvent(new Event('input'));
      }
    });
  },
});
// 只允许输入小数配合el-input 使用更佳 type值建议是text
Vue.directive('decimalNumber', {
  bind(el, binding, vnode) {
    let input = vnode.elm.children[0];
    input.addEventListener('compositionstart', () => {
      vnode.inputLocking = true;
    });
    input.addEventListener('compositionend', () => {
      vnode.inputLocking = false;
      input.dispatchEvent(new Event('input'));
    });
    input.addEventListener('input', () => {
      if (vnode.inputLocking) {
        return;
      }
      let oldValue = input.value;
      let newValue = input.value;
      newValue = newValue.replace(/[^\d.]/g, '');
      newValue = newValue.replace(/^\./g, '');
      newValue = newValue
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.');
      newValue = newValue.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
      if (newValue) {
        let arr = newValue.split('.');
        newValue = Number(arr[0]) + (arr[1] === undefined ? '' : '.' + arr[1]); // 去掉开头多余的0
      }
      // 判断是否需要更新，避免进入死循环
      if (newValue !== oldValue) {
        input.value = newValue;
        input.dispatchEvent(new Event('input')); // 通知v-model更新
      }
    });
    // input 事件无法处理小数点后面全是零的情况 因为无法确定用户输入的0是否真的应该清除，如3.02。放在blur中去处理
    input.addEventListener('blur', () => {
      let oldValue = input.value;
      let newValue = input.value;
      if (newValue) {
        newValue = Number(newValue).toString();
      }
      // 判断是否需要更新，避免进入死循环
      if (newValue !== oldValue) {
        input.value = newValue;
        input.dispatchEvent(new Event('input')); // 通知v-model更新
      }
    });
  },
});
